import { request } from '@/http';
import type { DetailsResponse, ListResponseWithPagination, Response } from '@/http';
import type { IAvailableCoupon } from '../restaurant-booking/interfaces/coupons';
import type { IPayment } from '../restaurant-booking/interfaces/payments';
import type { ISpaOrder } from '@/types/spaOrder';

/**
 * 创建预订单
 */
export async function createPreOrder(payload: ICreatePreOrderPayload) {
  const res = await request.post<Response<{ preOrderSn: string }>>(
    '/spa/order/createPreOrder',
    payload
  );
  return res.data.preOrderSn;
}

export interface ICreatePreOrderPayload {
  serviceId: number;
  serviceType: number;
  goodsId: number;
  bookDate: string;
  bookTime: string;
  propertyId?: number;
  roomNo?: string;
}

/**
 * 获取预创建订单详情
 */
export async function getPreOrderDetail(preOrderSn: string) {
  const res = await request.post<Response>('/spa/order/getPreOrderDetail', { preOrderSn });
  return res.data;
}

/**
 * 获取可用优惠券
 */
export async function getAvailableCoupons(preOrderSn: string) {
  const res = await request.post<
    Response<{
      list: IAvailableCoupon[];
      spaServiceTypeStr: string;
    }>
  >('/spa/order/orderCouponList', { preOrderSn });
  return res.data.list.filter((el) => el.use);
}

/**
 * 更改支付信息
 */
export function changePayment(payload: {
  preOrderSn: string;
  couponId?: number;
  isBalance?: boolean;
}) {
  return request.post<Response<IPayment>>('/spa/order/changePrePayInfo', payload);
}

/**
 * 创建订单
 */
export function createOrder(payload: ICreateOrderPayload) {
  return request.post<Response>('/spa/order/createOrder', payload);
}

export interface ICreateOrderPayload {
  preOrderSn: string;
  bookingName: string;
  bookingPhoneArea: string;
  bookingPhone: string;
  desc: string;
}

/**
 * 取消订单
 */
export function cancelOrder(orderSn: string) {
  return request.post<Response>('/spa/order/cancelOrder', { orderSn, formMember: true });
}

/**
 * 获取订单列表
 */
export async function getOrders(payload: IGetOrdersPayload) {
  const res = await request.post<ListResponseWithPagination<ISpaOrder>>(
    '/spa/order/orderList',
    payload
  );
  return res.data.list;
}

export interface IGetOrdersPayload {
  page: number;
  pageSize: number;
  orderStatus: string;
}

/**
 * 获取订单详情
 */
export async function getOrderDetail(orderSn: string) {
  const res = await request.post<DetailsResponse>('/spa/order/orderDetail', { orderSn });
  return res.data.detail;
}
